//
//  ViewController.m
//  KeepPwd
//
//  Created by 魏焜榕 on 2017/11/7.
//  Copyright © 2017年 LZH. All rights reserved.
//

#import "ViewController.h"
#import "CommonOC.h"
#import <LocalAuthentication/LocalAuthentication.h>

@interface ViewController ()<WKScriptMessageHandler>

@property (nonatomic, strong) WKWebView *wkWebView;
@property SystemSoundID soundID;
@property NSString *IKEY;
@property NSTimeInterval unlocktime;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSString *wavurlString = [NSString stringWithFormat:@"%@",[[NSBundle mainBundle] pathForResource:@"kr.wav" ofType:nil]];
    NSURL *wavurl = [NSURL URLWithString:wavurlString];
    SystemSoundID sid = 0;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)wavurl, &sid);
    self.soundID=sid;

    self.unlocktime=0;

    CFUUIDRef  uuidObj = CFUUIDCreate(nil);//create a new UUID
    self.IKEY = (__bridge_transfer NSString *)CFUUIDCreateString(nil, uuidObj);
    CFRelease(uuidObj);
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    //config.preferences.minimumFontSize = 18;
    
    self.wkWebView = [[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds configuration:config];
    self.view = self.wkWebView;
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html" subdirectory:@"html"];
    
    NSString *initIkey = [NSString stringWithFormat:@"_theIkey='%@';_NotShowPwd=0;_IsSupportFingerprint=%d",self.IKEY,[self IsSupportFingerprint]];
    
    [self.wkWebView loadFileURL:url allowingReadAccessToURL:url];
    [self.wkWebView evaluateJavaScript:initIkey completionHandler:nil];
    
    WKUserContentController *userCC = config.userContentController;
    //JS调用OC 添加处理脚本
    [userCC addScriptMessageHandler:self name:@"showMsg"];
    [userCC addScriptMessageHandler:self name:@"log"];
    [userCC addScriptMessageHandler:self name:@"actionSound"];
    [userCC addScriptMessageHandler:self name:@"copy"];
    [userCC addScriptMessageHandler:self name:@"socketSend"];
    [userCC addScriptMessageHandler:self name:@"unlock"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"%@",NSStringFromSelector(_cmd));
    NSLog(@"%@",message.body);
    
    if ([message.name isEqualToString:@"showMsg"]) {
        [self showMsg:message.body];
    }
    else if ([message.name isEqualToString:@"copy"]) {
        [self copy:message.body];
    }
    else if ([message.name isEqualToString:@"actionSound"]) {
        [self actionSound];
    }
    else if ([message.name isEqualToString:@"socketSend"]) {
        [NSThread detachNewThreadSelector:@selector(socketSend:) toTarget:self withObject:message.body];
    }
    else if ([message.name isEqualToString:@"unlock"]) {
        [self biologyAction];
    }
}

- (void)showMsg:(NSString *)msg {
    [[[UIAlertView alloc] initWithTitle:nil message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil] show];
}
- (void)copy:(NSString *)msg {
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = msg;
    [self showMsg:@"Copied successfully"];
}
- (void)actionSound{
    AudioServicesPlaySystemSound(self.soundID);
}
- (void)lock{
    NSTimeInterval now=[[NSDate date] timeIntervalSince1970];
    if(self.unlocktime==0||now-self.unlocktime>1){
        NSString *cmd = [NSString stringWithFormat:@"IFLock('%@');",self.IKEY];
        [self.wkWebView evaluateJavaScript:cmd completionHandler:nil];
    }
}
- (void)socketSend:(NSArray *)array{
    NSString* addr=array[0];
    NSString* portstr=array[1];
    NSString* msg=array[2];
    NSString* code=array[3];
    NSString* needCB=array[4];
    NSNumber * port = @([portstr integerValue]);
    
    NSString* res=[CCommonOC SocketSendAndRead:addr port:port code:code msg:msg];
    
    if(res == nil){
        [self performSelectorOnMainThread:@selector(showMsg:) withObject:@"Sent failed" waitUntilDone:NO];
    }
    else if([res isEqualToString:@"NoConnected"]){
        [self performSelectorOnMainThread:@selector(showMsg:) withObject:@"No client connected" waitUntilDone:NO];
    }
    else if([needCB isEqualToString:@"1"]){
        NSString *strUrl = [res stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];
        NSString *cmd = [NSString stringWithFormat:@"androidStWifiWithCBCallBack('%@');",strUrl];
        [self performSelectorOnMainThread:@selector(execScript:) withObject:cmd waitUntilDone:NO];
    }else{
        [self performSelectorOnMainThread:@selector(showMsg:) withObject:@"Sent successfully" waitUntilDone:NO];
    }
}

- (void)execScript:(NSString *)script {
    [self.wkWebView evaluateJavaScript:script completionHandler:nil];
}

- (int)IsSupportFingerprint{
    LAContext *context = [[LAContext alloc] init];
    NSError *error = nil;
    // 判断设置是否支持指纹识别(iPhone5s+、iOS8+支持)
    if([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]){
        return 1;
    }
    return 0;
}

- (IBAction)biologyAction {
    
    LAContext *context = [[LAContext alloc] init];
    NSError *error = nil;
    NSString *reason = @"我们需要验证您的指纹来确认您的身份";
    
    // 判断设置是否支持指纹识别(iPhone5s+、iOS8+支持)
    if([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]){
        
        // 指纹识别只判断当前用户是否是机主
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:reason reply:^(BOOL success, NSError * _Nullable error) {
            if(success){
                NSLog(@"指纹认证成功");
                self.unlocktime=[[NSDate date] timeIntervalSince1970];
                NSString *cmd = [NSString stringWithFormat:@"IFUnLock('%@');",self.IKEY];
                [self performSelectorOnMainThread:@selector(execScript:) withObject:cmd waitUntilDone:NO];
            }
            else{
                NSLog(@"指纹认证失败");
                NSLog(@"错误码：%zd",error.code);
                NSLog(@"出错信息：%@",error);
                // 错误码 error.code
                // -1: 连续三次指纹识别错误
                // -2: 在TouchID对话框中点击了取消按钮
                // -3: 在TouchID对话框中点击了输入密码按钮
                // -4: TouchID对话框被系统取消，例如按下Home或者电源键
                // -8: 连续五次指纹识别错误，TouchID功能被锁定，下一次需要输入系统密码
            }
        }];
    }
    else{
        NSLog(@"TouchID设备不可用");
        NSLog(@"错误码：%zd",error.code);
        NSLog(@"出错信息：%@",error);
    }
}

@end
